const { query } = require('../config/db');
const pricingEngine = require('../utils/pricingEngine');

/**
 * 安全解析JSON字段
 * @param {any} data - 要解析的数据
 * @param {any} defaultValue - 默认值
 * @param {string} fieldName - 字段名（用于日志）
 * @param {number} lotId - 停车场ID（用于日志）
 * @returns {any} 解析后的数据
 */
function safeParseJSON(data, defaultValue, fieldName, lotId) {
  try {
    if (data && typeof data === 'string') {
      return JSON.parse(data);
    } else if (data && typeof data === 'object') {
      return data;
    }
    return defaultValue;
  } catch (error) {
    console.warn(`解析${fieldName}失败:`, lotId, error.message);
    return defaultValue;
  }
}

/**
 * 处理停车场数据，安全解析JSON字段
 * @param {Array} parkingLots - 停车场数据数组
 * @returns {Array} 处理后的数据
 */
function processParkingLotsData(parkingLots) {
  return parkingLots.map(lot => ({
    ...lot,
    price_rules: safeParseJSON(lot.price_rules, {}, 'price_rules', lot.id),
    service_facilities: safeParseJSON(lot.service_facilities, [], 'service_facilities', lot.id),
    image_urls: safeParseJSON(lot.image_urls, [], 'image_urls', lot.id)
  }));
}

/**
 * 获取首页轮播图
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function getBanners(req, res) {
  try {
    // 从系统配置表获取轮播图配置
    const configQuery = 'SELECT config_value FROM system_configs WHERE config_key = ?';
    const configResult = await query(configQuery, ['homepage_carousel']);

    let banners = [];

    if (configResult.length > 0) {
      try {
        const configValue = configResult[0].config_value;
        const parsedData = JSON.parse(configValue);

        if (Array.isArray(parsedData)) {
          // 转换数据格式，添加id和其他字段
          banners = parsedData.map((item, index) => ({
            id: index + 1,
            title: `轮播图 ${index + 1}`,
            image: item.imageUrl,
            url: item.link || '',
            sort_order: index + 1,
            is_active: true
          })).filter(item => item.image); // 过滤掉没有图片的项
        }
      } catch (parseError) {
        console.warn('解析轮播图配置失败:', parseError);
      }
    }

    // 如果没有配置或配置为空，返回默认轮播图
    if (banners.length === 0) {
      banners = [
        {
          id: 1,
          title: '欢迎使用省米停车',
          image: '/static/banner1.jpg',
          url: '',
          sort_order: 1,
          is_active: true
        },
        {
          id: 2,
          title: '新用户专享优惠',
          image: '/static/banner2.jpg',
          url: '',
          sort_order: 2,
          is_active: true
        },
        {
          id: 3,
          title: '充电停车位优惠',
          image: '/static/banner3.jpg',
          url: '',
          sort_order: 3,
          is_active: true
        }
      ];
    }

    res.status(200).json({
      success: true,
      data: banners
    });

  } catch (error) {
    console.error('获取轮播图错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 获取停车场分类列表
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function getParkingCategories(req, res) {
  try {
    const categoriesQuery = `
      SELECT id, name, icon_url, sort_order
      FROM parking_lot_categories
      ORDER BY sort_order ASC, id ASC
    `;

    const categories = await query(categoriesQuery);

    res.status(200).json({
      success: true,
      data: categories
    });

  } catch (error) {
    console.error('获取停车场分类错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}



/**
 * 搜索停车场
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function searchParkingLots(req, res) {
  try {
    const { keyword, page = 1, limit = 10 } = req.query;

    if (!keyword || !keyword.trim()) {
      return res.status(400).json({
        success: false,
        message: '搜索关键词不能为空'
      });
    }

    const pageNum = parseInt(page) || 1;
    const limitNum = parseInt(limit) || 10;
    const offset = (pageNum - 1) * limitNum;
    const searchKeyword = `%${keyword.trim()}%`;

    let searchQuery = `
      SELECT
        p.*,
        c.name as category_name
    `;

    let whereClause = `
      FROM parking_lots p
      LEFT JOIN parking_lot_categories c ON p.category_id = c.id
      WHERE p.status = 'approved'
      AND (p.name LIKE ? OR p.address LIKE ? OR c.name LIKE ?)
    `;

    let queryParams = [searchKeyword, searchKeyword, searchKeyword];

    // 按创建时间排序
    whereClause += ` ORDER BY p.created_at DESC`;

    // 查询总数
    const countQuery = `SELECT COUNT(*) as total ${whereClause.replace(/ORDER BY.*$/, '')}`;
    const countResult = await query(countQuery, queryParams);
    const total = countResult[0].total;

    // 查询列表数据
    const listQuery = `${searchQuery} ${whereClause} LIMIT ${limitNum} OFFSET ${offset}`;
    const parkingLots = await query(listQuery, queryParams);

    // 处理返回数据
    const processedData = processParkingLotsData(parkingLots);

    res.status(200).json({
      success: true,
      data: {
        list: processedData,
        total,
        page: pageNum,
        limit: limitNum,
        totalPages: Math.ceil(total / limitNum)
      }
    });

  } catch (error) {
    console.error('搜索停车场错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 获取排序子句
 * @param {string} sortBy - 排序方式
 * @returns {string} 排序SQL子句
 */
function getSortClause(sortBy) {
  switch (sortBy) {
    case 'price':
      // 由于price_rules是JSON字段，我们按创建时间排序作为替代
      // 在实际应用中，可能需要更复杂的逻辑来处理价格排序
      return 'p.created_at DESC';
    case 'rating':
      // 如果有评分字段，可以在这里处理
      // 目前按创建时间排序作为替代
      return 'p.created_at DESC';

    case 'created_at':
    default:
      return 'p.created_at DESC';
  }
}

/**
 * 获取停车场列表（公开接口）
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function getParkingLots(req, res) {
  try {
    const {
      page = 1,
      limit = 10,
      keyword,
      categoryId,
      sortBy = 'created_at'
    } = req.query;

    const pageNum = parseInt(page) || 1;
    const limitNum = parseInt(limit) || 10;
    const offset = (pageNum - 1) * limitNum;

    let selectClause = `
      SELECT
        p.*,
        c.name as category_name
    `;

    let fromClause = `
      FROM parking_lots p
      LEFT JOIN parking_lot_categories c ON p.category_id = c.id
      WHERE p.status = 'approved'
    `;

    let queryParams = [];
    let whereConditions = [];

    // 关键词搜索
    if (keyword && keyword.trim()) {
      whereConditions.push('(p.name LIKE ? OR p.address LIKE ?)');
      const searchKeyword = `%${keyword.trim()}%`;
      queryParams.push(searchKeyword, searchKeyword);
    }

    // 分类筛选
    if (categoryId && !isNaN(categoryId)) {
      whereConditions.push('p.category_id = ?');
      queryParams.push(parseInt(categoryId));
    }

    // 添加额外的WHERE条件
    if (whereConditions.length > 0) {
      fromClause += ' AND ' + whereConditions.join(' AND ');
    }

    // 排序
    const orderClause = `ORDER BY ${getSortClause(sortBy)}`;

    // 查询总数
    const countQuery = `SELECT COUNT(*) as total ${fromClause}`;
    const countResult = await query(countQuery, queryParams);
    const total = countResult[0].total;

    // 查询列表数据
    const listQuery = `${selectClause} ${fromClause} ${orderClause} LIMIT ${limitNum} OFFSET ${offset}`;
    const parkingLots = await query(listQuery, queryParams);

    // 处理返回数据
    const processedData = processParkingLotsData(parkingLots);

    res.status(200).json({
      success: true,
      data: {
        list: processedData,
        total,
        page: pageNum,
        limit: limitNum,
        totalPages: Math.ceil(total / limitNum)
      }
    });

  } catch (error) {
    console.error('获取停车场列表错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 获取停车场详情（公开接口）
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function getParkingLotById(req, res) {
  try {
    const { id } = req.params;

    if (!id || isNaN(id)) {
      return res.status(400).json({
        success: false,
        message: '停车场ID无效'
      });
    }

    const parkingLotQuery = `
      SELECT
        p.*,
        c.name as category_name
      FROM parking_lots p
      LEFT JOIN parking_lot_categories c ON p.category_id = c.id
      WHERE p.id = ? AND p.status = 'approved'
    `;

    const result = await query(parkingLotQuery, [id]);

    if (result.length === 0) {
      return res.status(404).json({
        success: false,
        message: '停车场不存在或未审核通过'
      });
    }

    const parkingLot = result[0];

    // 查询评价信息（只显示可见的评价）
    const reviewsQuery = `
      SELECT
        r.id,
        r.rating,
        r.comment,
        r.created_at,
        u.nickname as user_nickname,
        u.avatar_url as user_avatar
      FROM reviews r
      LEFT JOIN users u ON r.user_id = u.id
      WHERE r.parking_lot_id = ? AND r.status = 'visible'
      ORDER BY r.created_at DESC
      LIMIT 10
    `;

    const reviews = await query(reviewsQuery, [id]);

    // 为每个评价查询回复
    for (let review of reviews) {
      const repliesQuery = `
        SELECT
          rr.id,
          rr.content,
          rr.created_at,
          u.nickname as reply_user_nickname
        FROM review_replies rr
        LEFT JOIN users u ON rr.user_id = u.id
        WHERE rr.review_id = ?
        ORDER BY rr.created_at ASC
      `;

      const replies = await query(repliesQuery, [review.id]);
      review.replies = replies;
    }

    // 计算评价统计
    const reviewStatsQuery = `
      SELECT
        COUNT(*) as total_reviews,
        AVG(rating) as average_rating,
        COUNT(CASE WHEN rating = 5 THEN 1 END) as five_star,
        COUNT(CASE WHEN rating = 4 THEN 1 END) as four_star,
        COUNT(CASE WHEN rating = 3 THEN 1 END) as three_star,
        COUNT(CASE WHEN rating = 2 THEN 1 END) as two_star,
        COUNT(CASE WHEN rating = 1 THEN 1 END) as one_star
      FROM reviews
      WHERE parking_lot_id = ? AND status = 'visible'
    `;

    const statsResult = await query(reviewStatsQuery, [id]);
    const reviewStats = statsResult[0] || {
      total_reviews: 0,
      average_rating: 0,
      five_star: 0,
      four_star: 0,
      three_star: 0,
      two_star: 0,
      one_star: 0
    };

    // 处理返回数据
    const processedData = processParkingLotsData([parkingLot])[0];

    // 添加评价信息
    processedData.reviews = reviews;
    processedData.review_stats = {
      total_reviews: reviewStats.total_reviews,
      average_rating: parseFloat(reviewStats.average_rating || 0).toFixed(1),
      rating_distribution: {
        five_star: reviewStats.five_star,
        four_star: reviewStats.four_star,
        three_star: reviewStats.three_star,
        two_star: reviewStats.two_star,
        one_star: reviewStats.one_star
      }
    };

    res.status(200).json({
      success: true,
      data: processedData
    });

  } catch (error) {
    console.error('获取停车场详情错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 获取推荐停车场
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function getRecommendedParkingLots(req, res) {
  try {
    const { limit = 10 } = req.query;
    const limitNum = parseInt(limit) || 10;

    const recommendedQuery = `
      SELECT
        p.*,
        c.name as category_name
      FROM parking_lots p
      LEFT JOIN parking_lot_categories c ON p.category_id = c.id
      WHERE p.status = 'approved'
      ORDER BY p.created_at DESC
      LIMIT ${limitNum}
    `;

    const parkingLots = await query(recommendedQuery, []);

    // 处理返回数据
    const processedData = processParkingLotsData(parkingLots);

    res.status(200).json({
      success: true,
      data: processedData
    });

  } catch (error) {
    console.error('获取推荐停车场错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 获取热门停车场（根据订单量排序）
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function getPopularParkingLots(req, res) {
  try {
    const { limit = 10, type = 'all' } = req.query;
    const limitNum = parseInt(limit) || 10;

    // 构建查询条件
    let whereCondition = "WHERE p.status = 'approved'";
    let queryParams = [];

    // 如果指定了类型，添加筛选条件
    if (type === 'airport') {
      whereCondition += " AND (p.name LIKE '%机场%' OR p.name LIKE '%航站%' OR p.address LIKE '%机场%')";
    } else if (type === 'railway') {
      whereCondition += " AND (p.name LIKE '%高铁%' OR p.name LIKE '%火车站%' OR p.name LIKE '%站%' OR p.address LIKE '%高铁%' OR p.address LIKE '%火车站%')";
    }

    const popularQuery = `
      SELECT
        p.*,
        c.name as category_name,
        COALESCE(order_stats.order_count, 0) as order_count,
        COALESCE(order_stats.total_revenue, 0) as total_revenue
      FROM parking_lots p
      LEFT JOIN parking_lot_categories c ON p.category_id = c.id
      LEFT JOIN (
        SELECT
          parking_lot_id,
          COUNT(*) as order_count,
          SUM(final_amount) as total_revenue
        FROM orders
        WHERE status IN ('confirmed', 'in_progress', 'completed')
          AND created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
        GROUP BY parking_lot_id
      ) order_stats ON p.id = order_stats.parking_lot_id
      ${whereCondition}
      ORDER BY order_stats.order_count DESC, p.created_at DESC
      LIMIT ${limitNum}
    `;

    const parkingLots = await query(popularQuery, queryParams);

    // 处理返回数据
    const processedData = processParkingLotsData(parkingLots);

    res.status(200).json({
      success: true,
      data: processedData
    });

  } catch (error) {
    console.error('获取热门停车场错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 计算停车费用（使用新的价格计算引擎）
 * @param {number} parkingLotId - 停车场ID
 * @param {Date|string} entryTime - 入场时间
 * @param {Date|string} exitTime - 出场时间
 * @returns {Promise<number>} 基础费用
 */
async function calculateParkingFee(parkingLotId, entryTime, exitTime) {
  try {
    // 使用新的价格计算引擎
    const priceResult = await pricingEngine.calculatePrice(parkingLotId, entryTime, exitTime);

    if (priceResult.success) {
      return priceResult.total_amount;
    } else {
      console.warn('价格计算失败，使用备用价格:', priceResult.error);
      return priceResult.fallback_amount || 50; // 使用备用价格
    }
  } catch (error) {
    console.error('价格计算错误:', error);
    // 计算备用价格：基于时长的简单计算
    const entryDate = new Date(entryTime);
    const exitDate = new Date(exitTime);
    const durationHours = (exitDate.getTime() - entryDate.getTime()) / (1000 * 60 * 60);
    return Math.ceil(durationHours / 24) * 50; // 每天50元的备用价格
  }
}

/**
 * 计算停车费用（兼容旧接口的包装函数）
 * @param {Object|Array} priceRules - 停车场价格规则（已废弃，保留兼容性）
 * @param {number} durationHours - 停车时长（小时）（已废弃，保留兼容性）
 * @returns {number} 基础费用
 */
function calculateParkingFeeLegacy(priceRules, durationHours) {
  try {
    // 这是为了向后兼容而保留的函数
    // 新代码应该使用 calculateParkingFee(parkingLotId, entryTime, exitTime)
    console.warn('使用了已废弃的价格计算函数，建议使用新的价格计算引擎');

    // 如果价格规则为空或无效，返回默认费用
    if (!priceRules || (typeof priceRules !== 'object' && !Array.isArray(priceRules))) {
      return Math.ceil(durationHours) * 5; // 默认每小时5元
    }

    let hourlyRate = 5; // 默认每小时5元
    let maxDailyRate = 50; // 默认日最高50元

    // 处理数组格式的价格规则（新格式）
    if (Array.isArray(priceRules) && priceRules.length > 0) {
      // 简化处理：使用第一个价格规则
      const firstRule = priceRules[0];
      if (firstRule && firstRule.price_per_hour) {
        hourlyRate = firstRule.price_per_hour;
      }
    }
    // 处理对象格式的价格规则（旧格式兼容）
    else if (typeof priceRules === 'object') {
      hourlyRate = priceRules.hourly_rate || priceRules.price_per_hour || 5;
      maxDailyRate = priceRules.max_daily_rate || priceRules.daily_max || 50;
    }

    // 计算基础费用（向上取整小时数）
    let baseFee = Math.ceil(durationHours) * hourlyRate;

    // 如果超过日最高费用，使用日最高费用
    const days = Math.ceil(durationHours / 24);
    const dailyMaxFee = days * maxDailyRate;

    return Math.min(baseFee, dailyMaxFee);
  } catch (error) {
    console.error('价格计算错误:', error);
    return Math.ceil(durationHours) * 5; // 出错时返回默认费用
  }
}

/**
 * 应用优惠券折扣
 * @param {number} baseAmount - 基础金额
 * @param {string} couponCode - 优惠券代码
 * @param {number} userId - 用户ID
 * @returns {Object} { discountAmount, finalAmount, couponInfo }
 */
async function applyCouponDiscount(baseAmount, couponCode, userId) {
  try {
    if (!couponCode || !userId) {
      return {
        discountAmount: 0,
        finalAmount: baseAmount,
        couponInfo: null
      };
    }

    // 解析优惠券代码，获取用户优惠券ID
    if (!couponCode.startsWith('UC_')) {
      return {
        discountAmount: 0,
        finalAmount: baseAmount,
        couponInfo: null,
        error: '优惠券代码格式无效'
      };
    }

    const userCouponId = couponCode.replace('UC_', '');

    // 查询用户优惠券信息
    const couponQuery = `
      SELECT
        uc.id as user_coupon_id,
        uc.status,
        uc.expiry_date,
        ct.name,
        ct.type,
        ct.value,
        ct.min_spend
      FROM user_coupons uc
      JOIN coupon_templates ct ON uc.template_id = ct.id
      WHERE uc.id = ? AND uc.user_id = ? AND uc.status = 'unused' AND uc.expiry_date > NOW()
    `;

    const couponResult = await query(couponQuery, [userCouponId, userId]);

    if (couponResult.length === 0) {
      return {
        discountAmount: 0,
        finalAmount: baseAmount,
        couponInfo: null,
        error: '优惠券不存在、已使用或已过期'
      };
    }

    const coupon = couponResult[0];

    // 检查最低消费
    if (baseAmount < coupon.min_spend) {
      return {
        discountAmount: 0,
        finalAmount: baseAmount,
        couponInfo: null,
        error: `此优惠券需要最低消费${coupon.min_spend}元`
      };
    }

    let discountAmount = 0;
    if (coupon.type === 'fixed') {
      discountAmount = Math.min(coupon.value, baseAmount);
    } else if (coupon.type === 'discount') {
      discountAmount = baseAmount * coupon.value;
    }

    return {
      discountAmount: Math.round(discountAmount * 100) / 100,
      finalAmount: Math.round((baseAmount - discountAmount) * 100) / 100,
      couponInfo: {
        user_coupon_id: coupon.user_coupon_id,
        code: couponCode,
        name: coupon.name,
        type: coupon.type,
        value: coupon.value
      }
    };

  } catch (error) {
    console.error('应用优惠券折扣错误:', error);
    return {
      discountAmount: 0,
      finalAmount: baseAmount,
      couponInfo: null,
      error: '优惠券处理失败'
    };
  }
}

/**
 * 生成订单号
 * @returns {string} 订单号
 */
function generateOrderNumber() {
  const timestamp = Date.now();
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
  return `PK${timestamp}${random}`;
}

/**
 * 创建停车订单
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function createOrder(req, res) {
  try {
    const {
      parking_lot_id,
      entry_time,
      exit_time,
      license_plate,
      contact_phone,
      coupon_code,
      parking_type = 'indoor'
    } = req.body;

    // 输入验证
    if (!parking_lot_id || !entry_time || !exit_time || !license_plate || !contact_phone) {
      return res.status(400).json({
        success: false,
        message: '缺少必要参数：停车场ID、入场时间、离场时间、车牌号、联系手机号'
      });
    }

    // 验证停车类型
    if (!['indoor', 'outdoor'].includes(parking_type)) {
      return res.status(400).json({
        success: false,
        message: '停车类型无效，必须是 indoor 或 outdoor'
      });
    }

    // 验证联系手机号格式
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(contact_phone)) {
      return res.status(400).json({
        success: false,
        message: '联系手机号格式不正确'
      });
    }

    // 验证时间
    const entryDate = new Date(entry_time);
    const exitDate = new Date(exit_time);
    const now = new Date();

    if (isNaN(entryDate.getTime()) || isNaN(exitDate.getTime())) {
      return res.status(400).json({
        success: false,
        message: '时间格式不正确'
      });
    }

    if (exitDate <= entryDate) {
      return res.status(400).json({
        success: false,
        message: '离场时间必须晚于入场时间'
      });
    }

    if (entryDate < now) {
      return res.status(400).json({
        success: false,
        message: '入场时间不能早于当前时间'
      });
    }

    // 获取停车场详情
    const parkingLotQuery = `
      SELECT id, name, price_rules, total_spaces
      FROM parking_lots
      WHERE id = ? AND status = 'approved'
    `;

    const parkingLotResult = await query(parkingLotQuery, [parking_lot_id]);

    if (parkingLotResult.length === 0) {
      return res.status(404).json({
        success: false,
        message: '停车场不存在或未审核通过'
      });
    }

    const parkingLot = parkingLotResult[0];

    // 解析价格规则
    let priceRules = {};
    try {
      priceRules = typeof parkingLot.price_rules === 'string'
        ? JSON.parse(parkingLot.price_rules)
        : parkingLot.price_rules;
    } catch (error) {
      console.error('解析价格规则失败:', error);
    }

    // 使用新的价格计算引擎计算基础费用（支持停车类型）
    const priceResult = await pricingEngine.calculatePrice(parking_lot_id, entry_time, exit_time, parking_type);

    if (!priceResult.success) {
      return res.status(400).json({
        success: false,
        message: '价格计算失败',
        error: priceResult.error
      });
    }

    const baseAmount = priceResult.total_amount;

    // 应用优惠券
    const userId = req.user ? req.user.id : null;
    const couponResult = await applyCouponDiscount(baseAmount, coupon_code, userId);

    if (couponResult.error) {
      return res.status(400).json({
        success: false,
        message: couponResult.error
      });
    }

    // 生成订单号
    const orderNumber = generateOrderNumber();

    // 创建订单记录（包含停车类型和联系手机号）
    const insertOrderQuery = `
      INSERT INTO orders (
        order_number, user_id, parking_lot_id, parking_type, license_plate, contact_phone,
        planned_start_time, planned_end_time, total_amount,
        discount_amount, final_amount, user_coupon_id, status, created_at, updated_at
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending_payment', NOW(), NOW())
    `;

    // 转换日期时间格式为MySQL可接受的格式
    // 保持本地时间，不进行时区转换
    const formatDateTimeForMySQL = (dateTimeStr) => {
      const date = new Date(dateTimeStr);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    };

    const insertResult = await query(insertOrderQuery, [
      orderNumber,
      req.user.id,
      parking_lot_id,
      parking_type,
      license_plate.toUpperCase(),
      contact_phone,
      formatDateTimeForMySQL(entry_time),
      formatDateTimeForMySQL(exit_time),
      baseAmount,
      couponResult.discountAmount,
      couponResult.finalAmount,
      couponResult.couponInfo ? couponResult.couponInfo.user_coupon_id : null
    ]);

    const orderId = insertResult.insertId;

    // 支付启动占位符
    console.log(`🚀 启动支付流程 - 订单ID: ${orderId}, 金额: ${couponResult.finalAmount}元`);

    // 发送订单通知短信（异步，不影响主流程）
    try {
      // 获取用户手机号
      const userQuery = 'SELECT phone_number FROM users WHERE id = ?';
      const userResult = await query(userQuery, [req.user.id]);

      if (userResult.length > 0 && userResult[0].phone_number) {
        const { sendOrderNotification } = require('../services/SmsService');

        // 构建订单详情
        const orderDetails = {
          order_number: orderNumber,
          license_plate: license_plate.toUpperCase(),
          parking_lot_name: parkingLot.name,
          planned_start_time: entry_time,
          planned_end_time: exit_time,
          final_amount: couponResult.finalAmount
        };

        // 异步发送短信，不等待结果
        sendOrderNotification(userResult[0].phone_number, orderDetails)
          .then(result => {
            if (result.success) {
              console.log(`✓ 订单通知短信发送成功 - 订单号: ${orderNumber}, 手机号: ${userResult[0].phone_number}`);
            } else if (!result.skip) {
              console.log(`✗ 订单通知短信发送失败 - 订单号: ${orderNumber}, 原因: ${result.message}`);
            }
          })
          .catch(error => {
            console.error(`✗ 订单通知短信发送异常 - 订单号: ${orderNumber}:`, error);
          });
      } else {
        console.log(`- 跳过短信通知 - 订单号: ${orderNumber}, 原因: 用户未绑定手机号`);
      }
    } catch (smsError) {
      // 短信发送错误不影响订单创建
      console.error('短信通知处理异常:', smsError);
    }

    // 发送订单通知邮件给停车场管理员（异步，不影响主流程）
    try {
      // 获取停车场管理员邮箱
      const managerQuery = `
        SELECT u.email, u.nickname
        FROM parking_lot_managers plm
        JOIN users u ON plm.user_id = u.id
        WHERE plm.parking_lot_id = ? AND u.email IS NOT NULL AND u.email != ''
      `;
      const managerResult = await query(managerQuery, [parking_lot_id]);

      if (managerResult.length > 0) {
        const { sendOrderNotificationToManager } = require('../services/EmailService');

        // 获取用户信息用于邮件通知
        const userQuery = 'SELECT nickname FROM users WHERE id = ?';
        const userResult = await query(userQuery, [req.user.id]);
        const userInfo = userResult.length > 0 ? userResult[0] : {};

        // 构建订单详情
        const orderDetails = {
          order_number: orderNumber,
          license_plate: license_plate.toUpperCase(),
          parking_lot_name: parkingLot.name,
          user_nickname: userInfo.nickname || '',
          user_phone: contact_phone, // 使用订单的联系手机号而不是注册手机号
          planned_start_time: entry_time,
          planned_end_time: exit_time,
          final_amount: couponResult.finalAmount,
          created_at: new Date()
        };

        // 向所有管理员发送邮件通知
        managerResult.forEach(manager => {
          sendOrderNotificationToManager(manager.email, orderDetails)
            .then(result => {
              if (result.success) {
                console.log(`✓ 订单通知邮件发送成功 - 订单号: ${orderNumber}, 管理员: ${manager.nickname || manager.email}`);
              } else if (!result.skip) {
                console.log(`✗ 订单通知邮件发送失败 - 订单号: ${orderNumber}, 管理员: ${manager.nickname || manager.email}, 原因: ${result.message}`);
              }
            })
            .catch(error => {
              console.error(`✗ 订单通知邮件发送异常 - 订单号: ${orderNumber}, 管理员: ${manager.nickname || manager.email}:`, error);
            });
        });
      } else {
        console.log(`- 跳过邮件通知 - 订单号: ${orderNumber}, 原因: 未找到停车场管理员邮箱`);
      }
    } catch (emailError) {
      // 邮件发送错误不影响订单创建
      console.error('邮件通知处理异常:', emailError);
    }

    // 计算停车天数用于显示
    const durationDays = pricingEngine.calculateParkingDays(entry_time, exit_time);

    // 返回订单详情
    res.status(201).json({
      success: true,
      message: '订单创建成功',
      data: {
        order_id: orderId,
        order_number: orderNumber,
        parking_lot_name: parkingLot.name,
        license_plate: license_plate.toUpperCase(),
        entry_time,
        exit_time,
        duration_days: durationDays,
        base_amount: baseAmount,
        discount_amount: couponResult.discountAmount,
        final_amount: couponResult.finalAmount,
        coupon_info: couponResult.couponInfo,
        status: 'pending_payment',
        payment_message: `请支付 ${couponResult.finalAmount} 元完成预定`
      }
    });

  } catch (error) {
    console.error('创建订单错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 获取停车价格预览（简化版本）
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function getParkingPrice(req, res) {
  try {
    const { parking_lot_id, entry_time, exit_time, coupon_code, parking_type = 'indoor' } = req.query;

    // 输入验证
    if (!parking_lot_id || !entry_time || !exit_time) {
      return res.status(400).json({
        success: false,
        message: '缺少必要参数：停车场ID、入场时间、离场时间'
      });
    }

    // 验证停车类型
    if (!['indoor', 'outdoor'].includes(parking_type)) {
      return res.status(400).json({
        success: false,
        message: '停车类型无效，必须是 indoor 或 outdoor'
      });
    }

    // 获取停车场详情
    const parkingLotQuery = `
      SELECT id, name, price_rules
      FROM parking_lots
      WHERE id = ? AND status = 'approved'
    `;

    const parkingLotResult = await query(parkingLotQuery, [parking_lot_id]);

    if (parkingLotResult.length === 0) {
      return res.status(404).json({
        success: false,
        message: '停车场不存在'
      });
    }

    const parkingLot = parkingLotResult[0];

    // 解析价格规则
    let priceRules = {};
    try {
      priceRules = typeof parkingLot.price_rules === 'string'
        ? JSON.parse(parkingLot.price_rules)
        : parkingLot.price_rules;
    } catch (error) {
      console.error('解析价格规则失败:', error);
    }

    // 使用新的价格计算引擎计算基础费用（支持停车类型）
    const priceResult = await pricingEngine.calculatePrice(parking_lot_id, entry_time, exit_time, parking_type);

    if (!priceResult.success) {
      return res.status(400).json({
        success: false,
        message: '价格计算失败',
        error: priceResult.error
      });
    }

    const baseAmount = priceResult.total_amount;
    const durationDays = priceResult.duration_days;

    // 应用优惠券
    const userId = req.user ? req.user.id : null;
    const couponResult = await applyCouponDiscount(baseAmount, coupon_code, userId);

    if (couponResult.error) {
      return res.status(400).json({
        success: false,
        message: couponResult.error
      });
    }

    // 检查是否启用了室内外分别定价
    const isIndoorOutdoorEnabled = await pricingEngine.isIndoorOutdoorPricingEnabled(parking_lot_id);

    const priceBreakdown = priceResult.price_breakdown;

    res.status(200).json({
      success: true,
      data: {
        parking_lot_name: parkingLot.name,
        parking_type: parking_type,
        duration_days: durationDays,
        base_amount: baseAmount,
        discount_amount: couponResult.discountAmount,
        final_amount: couponResult.finalAmount,
        coupon_info: couponResult.couponInfo,
        indoor_outdoor_enabled: await pricingEngine.isIndoorOutdoorPricingEnabled(parking_lot_id),
        price_breakdown: priceBreakdown || {
          days: durationDays,
          cumulative_price: baseAmount,
          description: `停车${durationDays}天，费用${baseAmount}元`,
          parking_type: parking_type
        }
      }
    });

  } catch (error) {
    console.error('获取停车价格错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 获取用户可用优惠券列表
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function getAvailableCoupons(req, res) {
  try {
    // 如果用户未登录，返回空列表
    if (!req.user || !req.user.id) {
      return res.status(200).json({
        success: true,
        data: []
      });
    }

    const userId = req.user.id;

    // 查询用户的可用优惠券（未使用且未过期）
    const couponQuery = `
      SELECT
        uc.id as user_coupon_id,
        uc.status,
        uc.issue_date,
        uc.expiry_date,
        ct.id as template_id,
        ct.name,
        ct.type,
        ct.value,
        ct.min_spend,
        ct.validity_type,
        ct.valid_days,
        ct.valid_start_date,
        ct.valid_end_date
      FROM user_coupons uc
      JOIN coupon_templates ct ON uc.template_id = ct.id
      WHERE uc.user_id = ?
        AND uc.status = 'unused'
        AND uc.expiry_date > NOW()
        AND ct.is_active = 1
      ORDER BY uc.expiry_date ASC
    `;

    const userCoupons = await query(couponQuery, [userId]);

    // 格式化优惠券数据
    const availableCoupons = userCoupons.map(coupon => {
      let description = '';
      if (coupon.type === 'fixed') {
        description = `满${coupon.min_spend}元可用，立减${coupon.value}元`;
      } else {
        const discount = Math.round((1 - coupon.value) * 10);
        description = `满${coupon.min_spend}元可用，享受${discount}折优惠`;
      }

      return {
        user_coupon_id: coupon.user_coupon_id,
        template_id: coupon.template_id,
        code: `UC_${coupon.user_coupon_id}`, // 生成唯一的优惠券代码
        name: coupon.name,
        type: coupon.type,
        value: coupon.value,
        min_spend: coupon.min_spend,
        description: description,
        expiry_date: coupon.expiry_date,
        issue_date: coupon.issue_date
      };
    });

    res.status(200).json({
      success: true,
      data: availableCoupons
    });

  } catch (error) {
    console.error('获取用户优惠券列表错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 验证优惠券
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function validateCoupon(req, res) {
  try {
    const { coupon_code, amount } = req.body;
    const userId = req.user ? req.user.id : null;

    if (!coupon_code) {
      return res.status(400).json({
        success: false,
        message: '请输入优惠券代码'
      });
    }

    if (!userId) {
      return res.status(401).json({
        success: false,
        message: '请先登录'
      });
    }

    const baseAmount = parseFloat(amount) || 0;
    const couponResult = await applyCouponDiscount(baseAmount, coupon_code, userId);

    if (couponResult.error) {
      return res.status(400).json({
        success: false,
        message: couponResult.error
      });
    }

    if (!couponResult.couponInfo) {
      return res.status(404).json({
        success: false,
        message: '优惠券不存在或已失效'
      });
    }

    res.status(200).json({
      success: true,
      message: '优惠券验证成功',
      data: {
        coupon_code,
        discount_amount: couponResult.discountAmount,
        final_amount: couponResult.finalAmount,
        coupon_info: couponResult.couponInfo
      }
    });

  } catch (error) {
    console.error('验证优惠券错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

// 支付订单 - 集成微信支付
const payOrder = async (req, res) => {
  try {
    const { orderId } = req.params;
    const { openid } = req.body; // 前端需要传递用户的openid
    const userId = req.user.id;

    console.log(`💳 处理支付请求 - 订单ID: ${orderId}, 用户ID: ${userId}`);

    // 验证订单是否存在且属于当前用户
    const orderQuery = `
      SELECT o.*, pl.name as parking_lot_name, pl.address as parking_lot_address
      FROM orders o
      LEFT JOIN parking_lots pl ON o.parking_lot_id = pl.id
      WHERE o.id = ? AND o.user_id = ?
    `;

    const orders = await query(orderQuery, [orderId, userId]);

    if (orders.length === 0) {
      return res.status(404).json({
        success: false,
        message: '订单不存在或无权限访问'
      });
    }

    const order = orders[0];

    // 检查订单状态
    if (order.status !== 'pending_payment') {
      return res.status(400).json({
        success: false,
        message: '订单状态不允许支付'
      });
    }

    // 检查是否提供了openid
    if (!openid) {
      return res.status(400).json({
        success: false,
        message: '缺少用户openid'
      });
    }

    // 在开发环境中，如果是模拟openid，使用模拟支付
    const isDevEnvironment = process.env.NODE_ENV === 'development';
    const isMockOpenid = openid.startsWith('mock_openid_');

    if (isDevEnvironment && isMockOpenid) {
      console.log('🎭 检测到开发环境和模拟openid，强制使用模拟支付');

      // 直接返回模拟支付参数
      const mockPaymentParams = {
        timeStamp: Math.floor(Date.now() / 1000).toString(),
        nonceStr: Math.random().toString(36).substr(2, 16),
        package: `prepay_id=mock_prepay_${Date.now()}`,
        signType: 'RSA',
        paySign: 'mock_pay_sign_' + Date.now(),
        mockMode: true
      };

      return res.json({
        success: true,
        message: '模拟支付下单成功',
        data: {
          order_id: orderId,
          order_number: order.order_number,
          amount: order.final_amount,
          payment_params: mockPaymentParams,
          mock_mode: true,
          mock_message: '开发环境检测到模拟openid，自动使用模拟支付'
        }
      });
    }

    // 调用微信支付下单接口
    const WechatPayService = require('../services/WechatPayService');

    const orderData = {
      description: `停车费用-${order.parking_lot_name}`,
      outTradeNo: order.order_number,
      amount: parseFloat(order.final_amount),
      openid: openid,
      timeExpire: new Date(Date.now() + 30 * 60 * 1000).toISOString() // 30分钟后过期
    };

    const payResult = await WechatPayService.createOrder(orderData);

    if (!payResult.success) {
      return res.status(400).json({
        success: false,
        message: `支付下单失败: ${payResult.error}`
      });
    }

    // 生成小程序支付参数
    const paymentParams = WechatPayService.generatePaymentParams(payResult.prepayId);

    console.log(`✅ 微信支付下单成功 - 订单: ${order.order_number}, prepayId: ${payResult.prepayId}`);

    // 如果是模拟模式，添加提示信息
    const responseData = {
      order_id: orderId,
      order_number: order.order_number,
      amount: order.final_amount,
      payment_params: paymentParams
    };

    if (paymentParams.mockMode) {
      responseData.mock_mode = true;
      responseData.mock_message = '当前为开发模式，请配置真实证书后切换到生产模式';
    }

    res.json({
      success: true,
      message: paymentParams.mockMode ? '模拟支付下单成功' : '支付下单成功',
      data: responseData
    });

  } catch (error) {
    console.error('支付订单错误:', error);
    res.status(500).json({
      success: false,
      message: '支付失败，请稍后重试'
    });
  }
};

// 支付尾款 - 延后离场补款
const payAdditionalAmount = async (req, res) => {
  try {
    const { orderId } = req.params;
    const { openid } = req.body; // 前端需要传递用户的openid
    const userId = req.user.id;

    console.log(`💳 处理尾款支付请求 - 订单ID: ${orderId}, 用户ID: ${userId}`);

    // 验证订单是否存在且属于当前用户
    const orderQuery = `
      SELECT o.*, pl.name as parking_lot_name, pl.address as parking_lot_address
      FROM orders o
      LEFT JOIN parking_lots pl ON o.parking_lot_id = pl.id
      WHERE o.id = ? AND o.user_id = ?
    `;

    const orders = await query(orderQuery, [orderId, userId]);
    if (orders.length === 0) {
      return res.status(404).json({ success: false, message: '订单不存在或无权限访问' });
    }

    const order = orders[0];

    // 检查订单状态
    if (order.status !== 'pending_additional_payment') {
      return res.status(400).json({ success: false, message: '订单状态不需要支付尾款' });
    }

    // 检查是否提供了openid
    if (!openid) {
      return res.status(400).json({ success: false, message: '缺少用户openid' });
    }

    // 计算应付尾款（重新计算后的总金额 - 原本已支付的金额）
    const newTotalAmount = parseFloat(order.total_amount);  // 重新计算后的总金额
    const originalPaidAmount = parseFloat(order.final_amount); // 原本已支付的金额
    const amountToPay = Math.max(0, Math.round((newTotalAmount - originalPaidAmount) * 100) / 100);

    if (amountToPay <= 0) {
      return res.status(400).json({ success: false, message: '无需支付尾款' });
    }

    const WechatPayService = require('../services/WechatPayService');

    // 生成用于尾款的唯一 out_trade_no，控制在32字节以内
    // 使用订单ID + 时间戳后6位来确保唯一性和长度限制
    const timestamp = Date.now().toString().slice(-6); // 取时间戳后6位
    const outTradeNo = `AD${orderId}T${timestamp}`; // 格式：AD{订单ID}T{时间戳后6位}

    const orderData = {
      description: `尾款-停车费用-${order.parking_lot_name}`,
      outTradeNo,
      amount: amountToPay,
      openid,
      timeExpire: new Date(Date.now() + 30 * 60 * 1000).toISOString()
    };

    const payResult = await WechatPayService.createOrder(orderData);

    if (!payResult.success) {
      return res.status(400).json({ success: false, message: `尾款下单失败: ${payResult.error}` });
    }

    const paymentParams = WechatPayService.generatePaymentParams(payResult.prepayId);

    // 写入 payment_method JSON，记录 additional_payments 列表
    let paymentMethodJson = {};
    try { paymentMethodJson = order.payment_method ? JSON.parse(order.payment_method) : {}; } catch (e) { paymentMethodJson = {}; }
    if (!paymentMethodJson.additional_payments) paymentMethodJson.additional_payments = [];
    paymentMethodJson.additional_payments.push({
      out_trade_no: outTradeNo,
      amount: amountToPay,
      status: 'PENDING',
      created_at: new Date().toISOString()
    });

    const updatePMQuery = `UPDATE orders SET payment_method = ?, updated_at = NOW() WHERE id = ?`;
    await query(updatePMQuery, [JSON.stringify(paymentMethodJson), orderId]);

    console.log(`✅ 尾款下单成功 - 订单: ${order.order_number}, 重新计算总金额: ${newTotalAmount}, 原已支付: ${originalPaidAmount}, 尾款: ${amountToPay}, prepayId: ${payResult.prepayId}`);

    res.json({
      success: true,
      message: paymentParams.mockMode ? '模拟尾款下单成功' : '尾款下单成功',
      data: {
        order_id: orderId,
        order_number: order.order_number,
        additional_amount: amountToPay,
        payment_params: paymentParams
      }
    });

  } catch (error) {
    console.error('尾款支付下单错误:', error);
    res.status(500).json({ success: false, message: '尾款支付失败，请稍后重试' });
  }
};


// 取消订单 - 完善版本，支持退款
const cancelOrder = async (req, res) => {
  try {
    const { orderId } = req.params;
    const { reason } = req.body; // 取消原因（可选）
    const userId = req.user.id;

    console.log(`❌ 处理取消订单请求 - 订单ID: ${orderId}, 用户ID: ${userId}`);

    // 验证订单是否存在且属于当前用户
    const orderQuery = `
      SELECT
        id, order_number, status, final_amount, total_amount, discount_amount,
        planned_start_time, planned_end_time, actual_start_time, actual_end_time,
        parking_lot_id, transaction_id, payment_method, paid_at, user_coupon_id
      FROM orders
      WHERE id = ? AND user_id = ?
    `;

    const orders = await query(orderQuery, [orderId, userId]);

    if (orders.length === 0) {
      return res.status(404).json({
        success: false,
        message: '订单不存在或无权限访问'
      });
    }

    const order = orders[0];

    // 检查订单状态，只有待支付和进行中的订单才能取消
    if (!['pending_payment', 'in_progress'].includes(order.status)) {
      return res.status(400).json({
        success: false,
        message: '当前订单状态不允许取消'
      });
    }

    // 检查时间限制：如果已经到达或超过预计停车时间，不允许自助取消
    const now = new Date();
    const plannedStartTime = new Date(order.planned_start_time);
    
    if (now >= plannedStartTime) {
      return res.status(400).json({
        success: false,
        message: '已到预计停车时间，请联系客服处理取消订单',
        requireCustomerService: true
      });
    }

    const refundCalculator = require('../utils/refundCalculator');
    const WechatPayService = require('../services/WechatPayService');

    let refundResult = null;
    let newStatus = 'cancelled';
    let refundInfo = null;

    // 如果订单已支付，需要处理退款
    if (order.status === 'in_progress' && order.paid_at) {
      // 计算退款金额
      const cancelTime = new Date();
      refundResult = await refundCalculator.calculateCancelRefund(order, cancelTime);

      if (!refundResult.success) {
        return res.status(400).json({
          success: false,
          message: `退款计算失败: ${refundResult.error}`
        });
      }

      if (refundResult.refundAmount > 0) {
        // 生成退款单号
        const refundNumber = refundCalculator.generateRefundNumber(order.order_number, 'RF');

        // 调用微信支付退款接口
        const wechatRefundResult = await WechatPayService.refund({
          transactionId: order.transaction_id,
          outRefundNo: refundNumber,
          reason: reason || refundResult.refundReason,
          refundAmount: refundResult.refundAmount,
          totalAmount: parseFloat(order.final_amount)
        });

        if (!wechatRefundResult.success) {
          return res.status(400).json({
            success: false,
            message: `退款申请失败: ${wechatRefundResult.error}`
          });
        }

        // 记录退款信息
        refundInfo = {
          refund_number: refundNumber,
          refund_amount: refundResult.refundAmount,
          service_fee: refundResult.serviceFee,
          refund_reason: refundResult.refundReason,
          refund_type: refundResult.refundType,
          wechat_refund_id: wechatRefundResult.refundId,
          refund_status: wechatRefundResult.status,
          refund_time: new Date().toISOString()
        };

        newStatus = 'cancelled';
      }
    }

    // 更新订单状态和退款信息
    const updateFields = ['status = ?', 'updated_at = NOW()'];
    const updateParams = [newStatus];

    // 将退款信息存储在payment_method字段中（JSON格式）
    if (refundInfo) {
      updateFields.push('payment_method = ?');
      updateParams.push(JSON.stringify({
        original_method: order.payment_method,
        refund_info: refundInfo
      }));
    }

    updateParams.push(orderId);

    const updateQuery = `
      UPDATE orders
      SET ${updateFields.join(', ')}
      WHERE id = ?
    `;

    await query(updateQuery, updateParams);

    // 如果使用了优惠券且需要退款，恢复优惠券状态
    if (refundInfo && order.user_coupon_id && refundResult.refundType === 'full_refund') {
      const restoreCouponQuery = `
        UPDATE user_coupons
        SET status = 'unused',
            used_at = NULL,
            order_id = NULL
        WHERE id = ? AND status = 'used'
      `;
      await query(restoreCouponQuery, [order.user_coupon_id]);
      console.log(`🎫 优惠券已恢复 - 优惠券ID: ${order.user_coupon_id}`);
    }

    console.log(`✅ 订单取消成功 - 订单: ${order.order_number}${refundInfo ? ', 退款金额: ' + refundInfo.refund_amount + '元' : ''}`);

    res.json({
      success: true,
      message: refundInfo ?
        `订单取消成功，退款${refundInfo.refund_amount}元${refundInfo.service_fee > 0 ? '（已扣除' + refundInfo.service_fee + '元服务费）' : ''}` :
        '订单取消成功',
      data: {
        order_id: orderId,
        order_number: order.order_number,
        status: newStatus,
        refund_info: refundInfo
      }
    });

  } catch (error) {
    console.error('取消订单错误:', error);
    res.status(500).json({
      success: false,
      message: '取消订单失败，请稍后重试'
    });
  }
};

// 获取用户订单列表
const getUserOrders = async (req, res) => {
  try {
    const userId = req.user.id;
    const {
      page = 1,
      limit = 10,
      status = ''
    } = req.query;

    console.log(`📋 获取用户订单 - 用户ID: ${userId}, 页码: ${page}, 状态: ${status}`);

    // 参数验证
    const pageNum = parseInt(page);
    const limitNum = parseInt(limit);

    if (pageNum < 1 || limitNum < 1 || limitNum > 50) {
      return res.status(400).json({
        success: false,
        message: '分页参数无效'
      });
    }

    // 构建查询条件
    let whereConditions = ['o.user_id = ?'];
    let queryParams = [userId];

    if (status.trim()) {
      whereConditions.push('o.status = ?');
      queryParams.push(status.trim());
    }

    const whereClause = whereConditions.length > 0 ?
      `WHERE ${whereConditions.join(' AND ')}` : '';

    // 查询总数
    const countQuery = `
      SELECT COUNT(*) as total
      FROM orders o
      ${whereClause}
    `;

    const countResult = await query(countQuery, queryParams);
    const total = countResult[0].total;

    // 查询订单列表
    const offset = (pageNum - 1) * limitNum;
    const listQuery = `
      SELECT
        o.id,
        o.order_number,
        o.parking_lot_id,
        o.parking_type,
        p.name as parking_lot_name,
        p.address as parking_lot_address,
        o.license_plate,
        o.planned_start_time,
        o.planned_end_time,
        o.actual_start_time,
        o.actual_end_time,
        o.total_amount,
        o.discount_amount,
        o.final_amount,
        o.status,
        o.payment_method,
        o.transaction_id,
        o.paid_at,
        o.created_at,
        o.updated_at
      FROM orders o
      LEFT JOIN parking_lots p ON o.parking_lot_id = p.id
      ${whereClause}
      ORDER BY o.created_at DESC
      LIMIT ${limitNum} OFFSET ${offset}
    `;

    const orders = await query(listQuery, queryParams);

    res.json({
      success: true,
      data: {
        list: orders,
        total,
        page: pageNum,
        limit: limitNum,
        totalPages: Math.ceil(total / limitNum)
      }
    });

  } catch (error) {
    console.error('获取用户订单错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
};

/**
 * 获取用户订单详情
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
const getUserOrderById = async (req, res) => {
  try {
    const userId = req.user.id;
    const orderId = parseInt(req.params.id);

    console.log(`📋 获取用户订单详情 - 用户ID: ${userId}, 订单ID: ${orderId}`);

    // 参数验证
    if (!orderId || orderId < 1) {
      return res.status(400).json({
        success: false,
        message: '订单ID无效'
      });
    }

    // 查询订单详情，包含停车场信息和评价信息
    const orderQuery = `
      SELECT
        o.id,
        o.order_number,
        o.parking_lot_id,
        o.parking_type,
        o.license_plate,
        o.contact_phone,
        o.planned_start_time,
        o.planned_end_time,
        o.actual_start_time,
        o.actual_end_time,
        o.total_amount,
        o.discount_amount,
        o.final_amount,
        o.status,
        o.payment_method,
        o.transaction_id,
        o.paid_at,
        o.created_at,
        o.updated_at,
        p.name as parking_lot_name,
        p.address as parking_lot_address,
        p.contact_phone as parking_lot_phone,
        p.service_facilities as parking_lot_facilities,
        uc.id as user_coupon_id,
        ct.name as coupon_name,
        ct.type as coupon_type,
        ct.value as coupon_discount_value,
        r.id as review_id,
        r.rating as review_rating,
        r.comment as review_comment,
        r.created_at as review_created_at
      FROM orders o
      LEFT JOIN parking_lots p ON o.parking_lot_id = p.id
      LEFT JOIN user_coupons uc ON o.user_coupon_id = uc.id
      LEFT JOIN coupon_templates ct ON uc.template_id = ct.id
      LEFT JOIN reviews r ON o.id = r.order_id
      WHERE o.id = ? AND o.user_id = ?
    `;

    const result = await query(orderQuery, [orderId, userId]);

    if (result.length === 0) {
      return res.status(404).json({
        success: false,
        message: '订单不存在或无权限查看'
      });
    }

    const orderData = result[0];

    // 构建响应数据
    const responseData = {
      id: orderData.id,
      order_number: orderData.order_number,
      status: orderData.status,
      parking_type: orderData.parking_type || 'indoor', // 添加停车类型，默认为indoor兼容旧数据
      license_plate: orderData.license_plate,
      contact_phone: orderData.contact_phone,
      planned_start_time: orderData.planned_start_time,
      planned_end_time: orderData.planned_end_time,
      actual_start_time: orderData.actual_start_time,
      actual_end_time: orderData.actual_end_time,
      total_amount: orderData.total_amount,
      discount_amount: orderData.discount_amount,
      final_amount: orderData.final_amount,
      payment_method: orderData.payment_method,
      transaction_id: orderData.transaction_id,
      paid_at: orderData.paid_at,
      created_at: orderData.created_at,
      updated_at: orderData.updated_at,
      parking_lot: {
        id: orderData.parking_lot_id,
        name: orderData.parking_lot_name,
        address: orderData.parking_lot_address,
        contact_phone: orderData.parking_lot_phone,
        service_facilities: safeParseJSON(orderData.parking_lot_facilities, [], 'service_facilities', orderData.parking_lot_id)
      }
    };

    // 添加优惠券信息（如果有）
    if (orderData.user_coupon_id) {
      responseData.coupon_info = {
        id: orderData.user_coupon_id,
        name: orderData.coupon_name,
        type: orderData.coupon_type,
        discount_value: orderData.coupon_discount_value,
        discount_amount: orderData.discount_amount
      };
    }

    // 添加评价信息（如果有）
    if (orderData.review_id) {
      responseData.review = {
        id: orderData.review_id,
        rating: orderData.review_rating,
        comment: orderData.review_comment,
        created_at: orderData.review_created_at
      };

      // 查询评价回复
      const repliesQuery = `
        SELECT
          rr.id,
          rr.content,
          rr.created_at,
          u.nickname as reply_user_nickname
        FROM review_replies rr
        LEFT JOIN users u ON rr.user_id = u.id
        WHERE rr.review_id = ?
        ORDER BY rr.created_at ASC
      `;

      const replies = await query(repliesQuery, [orderData.review_id]);
      responseData.review.replies = replies;
    }

    res.json({
      success: true,
      data: responseData
    });

  } catch (error) {
    console.error('获取用户订单详情错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
};

/**
 * 提交订单评价
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
const submitOrderReview = async (req, res) => {
  try {
    const userId = req.user.id;
    const orderId = parseInt(req.params.id);
    const { rating, comment } = req.body;

    console.log(`⭐ 提交订单评价 - 用户ID: ${userId}, 订单ID: ${orderId}, 评分: ${rating}`);

    // 参数验证
    if (!orderId || orderId < 1) {
      return res.status(400).json({
        success: false,
        message: '订单ID无效'
      });
    }

    if (!rating || rating < 1 || rating > 5) {
      return res.status(400).json({
        success: false,
        message: '评分必须在1-5之间'
      });
    }

    // 验证评价内容长度
    const reviewComment = comment ? comment.trim() : '';
    if (reviewComment.length > 500) {
      return res.status(400).json({
        success: false,
        message: '评价内容不能超过500字符'
      });
    }

    // 检查订单是否存在且属于当前用户
    const orderQuery = `
      SELECT id, parking_lot_id, status
      FROM orders
      WHERE id = ? AND user_id = ?
    `;
    const orderResult = await query(orderQuery, [orderId, userId]);

    if (orderResult.length === 0) {
      return res.status(404).json({
        success: false,
        message: '订单不存在或无权限操作'
      });
    }

    const order = orderResult[0];

    // 检查订单状态是否为已完成
    if (order.status !== 'completed') {
      return res.status(400).json({
        success: false,
        message: '只有已完成的订单才能评价'
      });
    }

    // 检查是否已经评价过
    const existingReviewQuery = `
      SELECT id FROM reviews WHERE order_id = ?
    `;
    const existingReview = await query(existingReviewQuery, [orderId]);

    if (existingReview.length > 0) {
      return res.status(400).json({
        success: false,
        message: '该订单已经评价过了'
      });
    }

    // 插入评价记录
    const insertReviewQuery = `
      INSERT INTO reviews (
        order_id, user_id, parking_lot_id, rating, comment, status
      ) VALUES (?, ?, ?, ?, ?, 'visible')
    `;

    const insertResult = await query(insertReviewQuery, [
      orderId,
      userId,
      order.parking_lot_id,
      rating,
      reviewComment
    ]);

    res.json({
      success: true,
      message: '评价提交成功',
      data: {
        review_id: insertResult.insertId,
        rating: rating,
        comment: reviewComment
      }
    });

  } catch (error) {
    console.error('提交订单评价错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
};

/**
 * 获取用户优惠券列表
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function getUserCoupons(req, res) {
  try {
    const userId = req.user.id;
    const {
      page = 1,
      limit = 10,
      status = ''
    } = req.query;

    console.log(`🎫 获取用户优惠券 - 用户ID: ${userId}, 页码: ${page}, 状态: ${status}`);

    // 参数验证
    const pageNum = parseInt(page);
    const limitNum = parseInt(limit);

    if (pageNum < 1 || limitNum < 1 || limitNum > 50) {
      return res.status(400).json({
        success: false,
        message: '分页参数无效'
      });
    }

    // 构建查询条件
    let whereConditions = ['uc.user_id = ?'];
    let queryParams = [userId];

    if (status.trim() && ['unused', 'used', 'expired'].includes(status.trim())) {
      whereConditions.push('uc.status = ?');
      queryParams.push(status.trim());
    }

    const whereClause = whereConditions.length > 0 ?
      `WHERE ${whereConditions.join(' AND ')}` : '';

    // 查询总数
    const countQuery = `
      SELECT COUNT(*) as total
      FROM user_coupons uc
      JOIN coupon_templates ct ON uc.template_id = ct.id
      ${whereClause}
    `;
    const countResult = await query(countQuery, queryParams);
    const total = countResult[0].total;

    // 查询列表数据
    const offset = (pageNum - 1) * limitNum;
    const listQuery = `
      SELECT
        uc.id as user_coupon_id,
        uc.status,
        uc.issue_date,
        uc.expiry_date,
        uc.used_at,
        uc.order_id,
        ct.id as template_id,
        ct.name,
        ct.type,
        ct.value,
        ct.min_spend,
        ct.validity_type
      FROM user_coupons uc
      JOIN coupon_templates ct ON uc.template_id = ct.id
      ${whereClause}
      ORDER BY uc.issue_date DESC
      LIMIT ${limitNum} OFFSET ${offset}
    `;

    queryParams.push(...queryParams); // 复制参数用于列表查询
    const coupons = await query(listQuery, queryParams.slice(0, queryParams.length / 2));

    // 格式化优惠券数据
    const formattedCoupons = coupons.map(coupon => {
      let description = '';
      if (coupon.type === 'fixed') {
        description = `满${coupon.min_spend}元可用，立减${coupon.value}元`;
      } else {
        const discount = Math.round((1 - coupon.value) * 10);
        description = `满${coupon.min_spend}元可用，享受${discount}折优惠`;
      }

      // 判断状态显示
      let statusText = '';
      switch (coupon.status) {
        case 'unused':
          statusText = new Date(coupon.expiry_date) > new Date() ? '未使用' : '已过期';
          break;
        case 'used':
          statusText = '已使用';
          break;
        case 'expired':
          statusText = '已过期';
          break;
      }

      return {
        user_coupon_id: coupon.user_coupon_id,
        template_id: coupon.template_id,
        code: `UC_${coupon.user_coupon_id}`,
        name: coupon.name,
        type: coupon.type,
        value: coupon.value,
        min_spend: coupon.min_spend,
        description: description,
        status: coupon.status,
        status_text: statusText,
        issue_date: coupon.issue_date,
        expiry_date: coupon.expiry_date,
        used_at: coupon.used_at,
        order_id: coupon.order_id
      };
    });

    res.json({
      success: true,
      data: {
        list: formattedCoupons,
        total,
        page: pageNum,
        limit: limitNum,
        totalPages: Math.ceil(total / limitNum)
      }
    });

  } catch (error) {
    console.error('获取用户优惠券错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 获取用户角色信息
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function getUserRole(req, res) {
  try {
    const userId = req.user.id;
    const { getUserRoleInfo } = require('../utils/roleAuth');

    const roleInfo = await getUserRoleInfo(userId);

    res.status(200).json({
      success: true,
      data: roleInfo
    });

  } catch (error) {
    console.error('获取用户角色信息错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 获取用户个人信息
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function getUserProfile(req, res) {
  try {
    const userId = req.user.id;
    
    // 查询用户信息
    const userQuery = `
      SELECT id, openid, nickname, avatar_url, phone_number, email, created_at
      FROM users
      WHERE id = ?
    `;
    
    const userResult = await query(userQuery, [userId]);
    
    if (userResult.length === 0) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }
    
    const user = userResult[0];
    
    res.status(200).json({
      success: true,
      data: {
        id: user.id,
        nickname: user.nickname,
        avatar_url: user.avatar_url,
        phone_number: user.phone_number,
        email: user.email,
        created_at: user.created_at
      }
    });
    
  } catch (error) {
    console.error('获取用户信息错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 检查用户是否已领取某类型优惠券
 * @param {number} userId - 用户ID
 * @param {number} templateId - 优惠券模板ID
 * @returns {Promise<boolean>} 是否已领取
 */
async function hasUserClaimed(userId, templateId) {
  try {
    const checkQuery = `
      SELECT COUNT(*) as count
      FROM user_coupons
      WHERE user_id = ? AND template_id = ?
    `;

    const result = await query(checkQuery, [userId, templateId]);
    return result[0].count > 0;
  } catch (error) {
    console.error('检查用户领取状态错误:', error);
    return false;
  }
}

/**
 * 计算优惠券过期时间
 * @param {Object} template - 优惠券模板
 * @returns {Date} 过期时间
 */
function calculateExpiryDate(template) {
  const now = new Date();

  if (template.validity_type === 'fixed_days') {
    const expiryDate = new Date(now);
    expiryDate.setDate(expiryDate.getDate() + (template.valid_days || 30));
    return expiryDate;
  } else if (template.validity_type === 'date_range') {
    return new Date(template.valid_end_date);
  }

  // 默认30天有效期
  const defaultExpiryDate = new Date(now);
  defaultExpiryDate.setDate(defaultExpiryDate.getDate() + 30);
  return defaultExpiryDate;
}

/**
 * 判断优惠券是否可领取
 * @param {Object} template - 优惠券模板
 * @param {number} userId - 用户ID
 * @returns {Promise<Object>} 可领取性结果
 */
async function canClaimCoupon(template, userId) {
  try {
    // 1. 检查模板是否启用
    if (!template.is_active) {
      return {
        canClaim: false,
        reason: 'disabled',
        message: '优惠券已停止发放'
      };
    }

    // 2. 检查库存
    if (template.total_quantity !== -1 &&
        template.issued_quantity >= template.total_quantity) {
      return {
        canClaim: false,
        reason: 'out_of_stock',
        message: '优惠券已被抢完'
      };
    }

    // 3. 检查用户是否已领取
    if (userId && await hasUserClaimed(userId, template.id)) {
      return {
        canClaim: false,
        reason: 'already_claimed',
        message: '您已领取过此类优惠券'
      };
    }

    // 4. 检查有效期（仅对日期范围类型）
    if (template.validity_type === 'date_range') {
      const now = new Date();
      const startDate = new Date(template.valid_start_date);
      const endDate = new Date(template.valid_end_date);

      if (now < startDate || now > endDate) {
        return {
          canClaim: false,
          reason: 'expired',
          message: '优惠券已过期或未到发放时间'
        };
      }
    }

    return {
      canClaim: true,
      reason: 'available',
      message: '可以领取'
    };
  } catch (error) {
    console.error('检查优惠券可领取性错误:', error);
    return {
      canClaim: false,
      reason: 'error',
      message: '检查失败，请稍后重试'
    };
  }
}

/**
 * 获取可领取的优惠券模板列表
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function getAvailableCouponTemplates(req, res) {
  try {
    const userId = req.user ? req.user.id : null;
    console.log('🎫 获取优惠券列表请求 - 用户ID:', userId);

    // 查询所有启用的优惠券模板
    const templatesQuery = `
      SELECT
        id,
        name,
        type,
        value,
        min_spend,
        validity_type,
        valid_days,
        valid_start_date,
        valid_end_date,
        total_quantity,
        issued_quantity,
        is_active,
        created_at
      FROM coupon_templates
      WHERE is_active = 1
      ORDER BY created_at DESC
    `;

    const templates = await query(templatesQuery);

    // 为每个模板检查可领取状态
    const availableTemplates = [];

    for (const template of templates) {
      const claimStatus = await canClaimCoupon(template, userId);

      // 计算剩余数量
      let remainingQuantity = null;
      if (template.total_quantity !== -1) {
        remainingQuantity = Math.max(0, template.total_quantity - template.issued_quantity);
      }

      // 格式化优惠券描述
      let description = '';
      if (template.type === 'fixed') {
        if (template.min_spend > 0) {
          description = `满${template.min_spend}元可用，立减${template.value}元`;
        } else {
          description = `无门槛立减${template.value}元`;
        }
      } else if (template.type === 'discount') {
        const discount = Math.round((1 - template.value) * 10);
        if (template.min_spend > 0) {
          description = `满${template.min_spend}元可用，享受${discount}折优惠`;
        } else {
          description = `无门槛${discount}折优惠`;
        }
      }

      // 格式化有效期描述
      let validityDescription = '';
      if (template.validity_type === 'fixed_days') {
        validityDescription = `领取后${template.valid_days || 30}天内有效`;
      } else if (template.validity_type === 'date_range') {
        const endDate = new Date(template.valid_end_date);
        validityDescription = `${endDate.toLocaleDateString('zh-CN')}前有效`;
      }

      availableTemplates.push({
        template_id: template.id,
        name: template.name,
        type: template.type,
        value: template.value,
        min_spend: template.min_spend,
        description: description,
        validity_type: template.validity_type,
        valid_days: template.valid_days,
        valid_start_date: template.valid_start_date,
        valid_end_date: template.valid_end_date,
        validity_description: validityDescription,
        total_quantity: template.total_quantity,
        issued_quantity: template.issued_quantity,
        remaining_quantity: remainingQuantity,
        can_claim: claimStatus.canClaim,
        claim_status: claimStatus.reason,
        claim_message: claimStatus.message,
        is_claimed: claimStatus.reason === 'already_claimed'
      });
    }

    res.status(200).json({
      success: true,
      data: availableTemplates
    });

  } catch (error) {
    console.error('获取可领取优惠券列表错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 领取优惠券
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function claimCoupon(req, res) {
  try {
    const { template_id } = req.body;
    const userId = req.user ? req.user.id : null;

    console.log('🎫 领取优惠券请求:', { template_id, userId, body: req.body, user: req.user });

    // 验证用户登录状态
    if (!userId) {
      console.log('❌ 用户未登录');
      return res.status(401).json({
        success: false,
        message: '请先登录'
      });
    }

    // 验证参数
    if (!template_id || isNaN(template_id)) {
      console.log('❌ 参数验证失败:', { template_id, isNaN: isNaN(template_id) });
      return res.status(400).json({
        success: false,
        message: '优惠券模板ID无效'
      });
    }

    // 获取优惠券模板信息
    const templateQuery = `
      SELECT
        id, name, type, value, min_spend, validity_type,
        valid_days, valid_start_date, valid_end_date,
        total_quantity, issued_quantity, is_active
      FROM coupon_templates
      WHERE id = ?
    `;

    const templateResult = await query(templateQuery, [template_id]);

    console.log('📋 查询模板结果:', templateResult);

    if (templateResult.length === 0) {
      console.log('❌ 优惠券模板不存在');
      return res.status(404).json({
        success: false,
        message: '优惠券模板不存在'
      });
    }

    const template = templateResult[0];
    console.log('🎯 找到模板:', template);

    // 检查是否可以领取
    const claimStatus = await canClaimCoupon(template, userId);
    console.log('🔍 领取状态检查:', claimStatus);

    if (!claimStatus.canClaim) {
      console.log('❌ 不能领取:', claimStatus.message);
      return res.status(400).json({
        success: false,
        message: claimStatus.message
      });
    }

    console.log('💾 开始数据库操作...');

    try {
      // 计算过期时间
      const expiryDate = calculateExpiryDate(template);
      console.log('📅 计算过期时间:', expiryDate);

      // 创建用户优惠券记录
      const insertUserCouponQuery = `
        INSERT INTO user_coupons (
          user_id, template_id, status, issue_date, expiry_date
        ) VALUES (?, ?, 'unused', NOW(), ?)
      `;

      console.log('📝 插入用户优惠券记录...');
      const insertResult = await query(insertUserCouponQuery, [
        userId, template_id, expiryDate
      ]);

      console.log('✅ 用户优惠券记录创建成功:', insertResult.insertId);

      // 更新模板发放数量
      const updateTemplateQuery = `
        UPDATE coupon_templates
        SET issued_quantity = issued_quantity + 1,
            updated_at = NOW()
        WHERE id = ?
      `;

      console.log('🔄 更新模板发放数量...');
      await query(updateTemplateQuery, [template_id]);

      console.log('🎉 优惠券领取成功！');

      res.status(200).json({
        success: true,
        message: '优惠券领取成功',
        data: {
          user_coupon_id: insertResult.insertId,
          coupon_name: template.name,
          expiry_date: expiryDate.toISOString().slice(0, 19).replace('T', ' ')
        }
      });

    } catch (dbError) {
      console.error('💥 数据库操作失败:', dbError);
      throw dbError;
    }

  } catch (error) {
    console.error('领取优惠券错误:', error);

    // 检查是否是重复领取错误
    if (error.code === 'ER_DUP_ENTRY') {
      return res.status(400).json({
        success: false,
        message: '您已领取过此类优惠券'
      });
    }

    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 获取客服配置信息
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function getCustomerServiceConfig(req, res) {
  try {
    // 获取客服相关配置
    const configKeys = [
      'customer_service_wechat',
      'customer_service_phone',
      'customer_service_qrcode'
    ];

    const configQueries = configKeys.map(key =>
      query('SELECT config_key, config_value FROM system_configs WHERE config_key = ?', [key])
    );

    const results = await Promise.all(configQueries);

    // 处理结果
    const serviceConfig = {
      wechat: '',
      phone: '',
      qrcode: ''
    };

    results.forEach((result, index) => {
      if (result.length > 0) {
        const key = configKeys[index];
        const value = result[0].config_value;

        switch (key) {
          case 'customer_service_wechat':
            serviceConfig.wechat = value;
            break;
          case 'customer_service_phone':
            serviceConfig.phone = value;
            break;
          case 'customer_service_qrcode':
            serviceConfig.qrcode = value;
            break;
        }
      }
    });

    // 设置默认值
    if (!serviceConfig.phone) {
      serviceConfig.phone = '400-123-4567';
    }
    if (!serviceConfig.wechat) {
      serviceConfig.wechat = 'parking_service';
    }

    res.json({
      success: true,
      data: serviceConfig
    });

  } catch (error) {
    console.error('获取客服配置错误:', error);
    res.status(500).json({
      success: false,
      message: '获取客服配置失败'
    });
  }
}

// 微信支付回调处理
const handlePaymentNotify = async (req, res) => {
  try {
    const WechatPayService = require('../services/WechatPayService');

    // 验证签名
    const isValid = WechatPayService.verifyNotifySignature(req.headers, JSON.stringify(req.body));

    if (!isValid) {
      console.error('❌ 支付回调签名验证失败');
      return res.status(400).json({ code: 'FAIL', message: '签名验证失败' });
    }

    // 解密回调数据
    const decryptedData = WechatPayService.decryptNotifyData(req.body.resource);

    console.log('📨 收到支付回调:', decryptedData);

    const { out_trade_no, trade_state, transaction_id, amount } = decryptedData;

    if (trade_state === 'SUCCESS') {
      // 优先处理正常首款支付（待支付 -> 进行中）
      const updateQuery = `
        UPDATE orders
        SET status = 'in_progress',
            paid_at = NOW(),
            payment_method = 'wechat_pay',
            transaction_id = ?,
            updated_at = NOW()
        WHERE order_number = ? AND status = 'pending_payment'
      `;

      const updateResult = await query(updateQuery, [transaction_id, out_trade_no]);

      if (updateResult.affectedRows > 0) {
        console.log(`✅ 订单支付成功 - 订单号: ${out_trade_no}, 交易ID: ${transaction_id}`);

        // 更新优惠券状态（如果有使用）
        const orderQuery = `SELECT id, user_coupon_id FROM orders WHERE order_number = ?`;
        const orders = await query(orderQuery, [out_trade_no]);

        if (orders.length > 0 && orders[0].user_coupon_id) {
          const updateCouponQuery = `
            UPDATE user_coupons
            SET status = 'used',
                used_at = NOW(),
                order_id = ?
            WHERE id = ? AND status = 'unused'
          `;
          await query(updateCouponQuery, [orders[0].id, orders[0].user_coupon_id]);
        }
      } else {
        // 可能为“尾款支付”场景：在 payment_method JSON 中查找 additional_payments 记录
        const paidYuan = amount?.payer_total ? amount.payer_total / 100 : (amount?.total ? amount.total / 100 : 0);

        const findOrderByAdditional = `
          SELECT id, order_number, total_amount, final_amount, discount_amount, payment_method, status, actual_end_time
          FROM orders
          WHERE payment_method LIKE ?
          LIMIT 1
        `;
        const candidates = await query(findOrderByAdditional, [`%${out_trade_no}%`]);

        if (candidates.length > 0) {
          const order = candidates[0];
          let pm = {};
          try { pm = order.payment_method ? JSON.parse(order.payment_method) : {}; } catch (e) { pm = {}; }
          if (!Array.isArray(pm.additional_payments)) pm.additional_payments = [];

          // 标记对应记录为成功
          pm.additional_payments = pm.additional_payments.map(rec => {
            if (rec.out_trade_no === out_trade_no) {
              return { ...rec, status: 'SUCCESS', transaction_id, paid_amount: paidYuan, paid_at: new Date().toISOString() };
            }
            return rec;
          });

          const totalAmount = parseFloat(order.total_amount);
          const currentFinal = parseFloat(order.final_amount);
          const discountAmount = parseFloat(order.discount_amount) || 0;
          const newFinal = Math.round((currentFinal + paidYuan) * 100) / 100;
          // 计算应付金额：总费用 - 优惠券折扣（优惠券永久有效）
          const shouldPayAmount = Math.max(0, totalAmount - discountAmount);
          const shouldComplete = newFinal >= shouldPayAmount - 0.005;

          // 若已补齐且存在实际离场时间，则直接完成订单
          const newStatus = shouldComplete ? (order.actual_end_time ? 'completed' : 'in_progress') : 'pending_additional_payment';

          const updateAdditionalQuery = `
            UPDATE orders
            SET final_amount = ?,
                status = ?,
                payment_method = ?,
                updated_at = NOW()
            WHERE id = ?
          `;
          await query(updateAdditionalQuery, [shouldComplete ? shouldPayAmount : newFinal, newStatus, JSON.stringify(pm), order.id]);

          console.log(`✅ 尾款支付成功 - 订单号: ${order.order_number}, 本次支付: ${paidYuan}元, 累计实付: ${shouldComplete ? shouldPayAmount : newFinal}元, 状态: ${newStatus}`);
        } else {
          console.warn(`⚠️ 未找到与 out_trade_no=${out_trade_no} 匹配的订单（非首款支付也非记录在案的尾款）`);
        }
      }
    }

    // 返回成功响应
    res.json({ code: 'SUCCESS', message: '成功' });

  } catch (error) {
    console.error('处理支付回调错误:', error);
    res.status(500).json({ code: 'FAIL', message: '处理失败' });
  }
};

// 微信支付退款回调处理
const handleRefundNotify = async (req, res) => {
  try {
    const WechatPayService = require('../services/WechatPayService');
    const refundRecordService = require('../services/refundRecordService');

    // 验证退款回调签名
    const isValid = WechatPayService.verifyRefundNotifySignature(req.headers, JSON.stringify(req.body));

    if (!isValid) {
      console.error('❌ 退款回调签名验证失败');
      return res.status(400).json({ code: 'FAIL', message: '签名验证失败' });
    }

    // 解密回调数据
    const decryptedData = WechatPayService.decryptNotifyData(req.body.resource);

    console.log('📨 收到退款回调:', decryptedData);

    const {
      out_refund_no,
      refund_status,
      refund_id,
      out_trade_no,
      amount
    } = decryptedData;

    // 根据退款单号查找对应的订单
    const orderQuery = `
      SELECT id, order_number, payment_method
      FROM orders
      WHERE payment_method LIKE ? AND payment_method LIKE ?
    `;

    const orders = await query(orderQuery, [`%${out_refund_no}%`, '%refund_records%']);

    if (orders.length > 0) {
      const order = orders[0];

      // 更新退款状态
      const updateResult = await refundRecordService.updateRefundStatus(
        order.id,
        out_refund_no,
        refund_status,
        {
          wechat_refund_id: refund_id,
          refund_amount: amount ? amount.refund / 100 : null, // 微信返回的是分，转换为元
          callback_time: new Date().toISOString()
        }
      );

      if (updateResult.success) {
        console.log(`✅ 退款回调处理成功 - 订单: ${order.order_number}, 退款单号: ${out_refund_no}, 状态: ${refund_status}`);
      } else {
        console.error(`❌ 退款状态更新失败 - 订单: ${order.order_number}, 错误: ${updateResult.error}`);
      }
    } else {
      console.warn(`⚠️ 未找到对应的退款记录 - 退款单号: ${out_refund_no}`);
    }

    // 返回成功响应
    res.json({ code: 'SUCCESS', message: '成功' });

  } catch (error) {
    console.error('处理退款回调错误:', error);
    res.status(500).json({ code: 'FAIL', message: '处理失败' });
  }
};

// 模拟支付成功（仅开发模式）
const mockPaymentSuccess = async (req, res) => {
  try {
    const { orderId } = req.params;
    const userId = req.user.id;

    // 检查是否为模拟模式
    if (process.env.PAYMENT_MOCK_MODE !== 'true') {
      return res.status(403).json({
        success: false,
        message: '此接口仅在开发模式下可用'
      });
    }

    console.log(`🎭 模拟支付成功 - 订单ID: ${orderId}, 用户ID: ${userId}`);

    // 验证订单是否存在且属于当前用户
    const orderQuery = `
      SELECT id, order_number, final_amount, status, user_coupon_id
      FROM orders
      WHERE id = ? AND user_id = ?
    `;

    const orders = await query(orderQuery, [orderId, userId]);

    if (orders.length === 0) {
      return res.status(404).json({
        success: false,
        message: '订单不存在或无权限访问'
      });
    }

    const order = orders[0];

    // 检查订单状态
    if (order.status !== 'pending_payment') {
      return res.status(400).json({
        success: false,
        message: '订单状态不允许支付'
      });
    }

    // 更新订单状态为已支付
    const transactionId = `MOCK_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;

    const updateQuery = `
      UPDATE orders
      SET status = 'in_progress',
          paid_at = NOW(),
          payment_method = 'mock_wechat_pay',
          transaction_id = ?,
          updated_at = NOW()
      WHERE id = ?
    `;

    await query(updateQuery, [transactionId, orderId]);

    // 如果订单使用了优惠券，更新优惠券状态为已使用
    if (order.user_coupon_id) {
      const updateCouponQuery = `
        UPDATE user_coupons
        SET status = 'used',
            used_at = NOW(),
            order_id = ?
        WHERE id = ? AND status = 'unused'
      `;

      const couponUpdateResult = await query(updateCouponQuery, [orderId, order.user_coupon_id]);

      if (couponUpdateResult.affectedRows > 0) {
        console.log(`🎫 优惠券已标记为已使用 - 优惠券ID: ${order.user_coupon_id}, 订单: ${order.order_number}`);
      }
    }

    console.log(`✅ 模拟支付成功 - 订单: ${order.order_number}, 交易ID: ${transactionId}`);

    res.json({
      success: true,
      message: '模拟支付成功',
      data: {
        order_id: orderId,
        order_number: order.order_number,
        transaction_id: transactionId,
        amount: order.final_amount,
        status: 'in_progress',
        mock_mode: true
      }
    });

  } catch (error) {
    console.error('模拟支付错误:', error);
    res.status(500).json({
      success: false,
      message: '模拟支付失败'
    });
  }
};

// 获取用户openid
const getOpenid = async (req, res) => {
  try {
    const { code } = req.body;

    if (!code) {
      return res.status(400).json({
        success: false,
        message: '缺少登录凭证code'
      });
    }

    // 检查是否为开发环境的模拟code
    if (code.startsWith('mock_code_') || process.env.NODE_ENV === 'development') {
      console.log('🎭 开发环境检测到，返回模拟openid');
      return res.json({
        success: true,
        data: {
          openid: 'mock_openid_' + Date.now(),
          session_key: 'mock_session_key'
        }
      });
    }

    const WechatAuthService = require('../services/WechatAuthService');
    const result = await WechatAuthService.getOpenidByCode(code);

    if (result.success) {
      res.json({
        success: true,
        data: {
          openid: result.data.openid,
          session_key: result.data.session_key
        }
      });
    } else {
      // 如果微信API调用失败，在开发环境中返回模拟数据
      if (process.env.NODE_ENV === 'development') {
        console.log('🎭 微信API调用失败，开发环境返回模拟openid');
        return res.json({
          success: true,
          data: {
            openid: 'mock_openid_' + Date.now(),
            session_key: 'mock_session_key'
          }
        });
      }

      res.status(400).json({
        success: false,
        message: result.error
      });
    }

  } catch (error) {
    console.error('获取openid错误:', error);

    // 在开发环境中，即使出错也返回模拟数据
    if (process.env.NODE_ENV === 'development') {
      console.log('🎭 获取openid出错，开发环境返回模拟openid');
      return res.json({
        success: true,
        data: {
          openid: 'mock_openid_' + Date.now(),
          session_key: 'mock_session_key'
        }
      });
    }

    res.status(500).json({
      success: false,
      message: '获取openid失败'
    });
  }
};

// 微信小程序登录
const wxLogin = async (req, res) => {
  try {
    const { code, userInfo = {} } = req.body;

    if (!code) {
      return res.status(400).json({
        success: false,
        message: '缺少登录凭证code'
      });
    }

    console.log('🔐 微信登录请求 - code:', code.substring(0, 10) + '...');

    let openid, sessionKey;

    // 检查是否为开发环境的模拟code
    if (code.startsWith('mock_code_') || process.env.NODE_ENV === 'development') {
      console.log('🎭 开发环境检测到，使用模拟openid');
      openid = 'mock_openid_' + Date.now();
      sessionKey = 'mock_session_key';
    } else {
      // 获取微信用户openid
      const WechatAuthService = require('../services/WechatAuthService');
      const result = await WechatAuthService.getOpenidByCode(code);

      if (result.success) {
        openid = result.data.openid;
        sessionKey = result.data.session_key;
      } else {
        // 如果微信API调用失败，在开发环境中使用模拟数据
        if (process.env.NODE_ENV === 'development') {
          console.log('🎭 微信API调用失败，开发环境使用模拟openid');
          openid = 'mock_openid_' + Date.now();
          sessionKey = 'mock_session_key';
        } else {
          return res.status(400).json({
            success: false,
            message: result.error || '微信登录失败'
          });
        }
      }
    }

    // 查询或创建用户
    const userQuery = 'SELECT * FROM users WHERE openid = ?';
    const existingUsers = await query(userQuery, [openid]);

    let user;
    if (existingUsers.length > 0) {
      // 用户已存在，更新用户信息
      user = existingUsers[0];

      // 如果提供了用户信息，更新数据库
      if (userInfo.nickName || userInfo.avatarUrl) {
        const updateQuery = `
          UPDATE users
          SET nickname = ?, avatar_url = ?
          WHERE id = ?
        `;
        await query(updateQuery, [
          userInfo.nickName || user.nickname,
          userInfo.avatarUrl || user.avatar_url,
          user.id
        ]);

        // 重新获取更新后的用户信息
        const updatedUsers = await query(userQuery, [openid]);
        user = updatedUsers[0];
      }
    } else {
      // 创建新用户
      const insertQuery = `
        INSERT INTO users (openid, nickname, avatar_url, created_at)
        VALUES (?, ?, ?, NOW())
      `;

      const insertResult = await query(insertQuery, [
        openid,
        userInfo.nickName || '微信用户',
        userInfo.avatarUrl || ''
      ]);

      // 获取新创建的用户信息
      const newUsers = await query('SELECT * FROM users WHERE id = ?', [insertResult.insertId]);
      user = newUsers[0];
    }

    // 生成JWT token
    const jwt = require('jsonwebtoken');
    const token = jwt.sign(
      {
        id: user.id,
        openid: user.openid,
        type: 'user'
      },
      process.env.JWT_SECRET || 'your-secret-key',
      { expiresIn: '30d' }
    );

    // 返回登录成功信息
    res.json({
      success: true,
      message: '登录成功',
      data: {
        token,
        userInfo: {
          id: user.id,
          nickname: user.nickname,
          avatar: user.avatar_url,
          phone: user.phone_number || '',
          openid: user.openid
        }
      }
    });

    console.log('✅ 微信登录成功 - 用户ID:', user.id, '昵称:', user.nickname);

  } catch (error) {
    console.error('微信登录错误:', error);

    // 在开发环境中，即使出错也尝试返回模拟登录
    if (process.env.NODE_ENV === 'development') {
      console.log('🎭 微信登录出错，开发环境返回模拟登录');

      const jwt = require('jsonwebtoken');
      const mockUser = {
        id: 999,
        nickname: '开发测试用户',
        avatar_url: '',
        openid: 'mock_openid_dev'
      };

      const token = jwt.sign(
        {
          id: mockUser.id,
          openid: mockUser.openid,
          type: 'user'
        },
        process.env.JWT_SECRET || 'your-secret-key',
        { expiresIn: '30d' }
      );

      return res.json({
        success: true,
        message: '开发环境模拟登录成功',
        data: {
          token,
          userInfo: {
            id: mockUser.id,
            nickname: mockUser.nickname,
            avatar: mockUser.avatar_url,
            phone: '',
            openid: mockUser.openid
          }
        }
      });
    }

    res.status(500).json({
      success: false,
      message: '登录失败，请重试'
    });
  }
};

// 查询支付状态
const queryPaymentStatus = async (req, res) => {
  try {
    const { orderId } = req.params;
    const userId = req.user.id;

    // 获取订单信息
    const orderQuery = `
      SELECT order_number, status, final_amount, total_amount, transaction_id, payment_method
      FROM orders
      WHERE id = ? AND user_id = ?
    `;

    const orders = await query(orderQuery, [orderId, userId]);

    if (orders.length === 0) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }

    const order = orders[0];

    // 如果订单不是待支付或待补款状态，直接返回当前状态
    if (!['pending_payment', 'pending_additional_payment'].includes(order.status)) {
      return res.json({
        success: true,
        data: {
          order_number: order.order_number,
          status: order.status,
          amount: order.final_amount,
          transaction_id: order.transaction_id
        }
      });
    }

    const WechatPayService = require('../services/WechatPayService');

    // 处理正常订单支付状态查询
    if (order.status === 'pending_payment') {
      const payResult = await WechatPayService.queryOrder(order.order_number);

      if (payResult.success && payResult.data.trade_state === 'SUCCESS') {
        // 更新本地订单状态
        const updateQuery = `
          UPDATE orders
          SET status = 'in_progress',
              paid_at = NOW(),
              payment_method = 'wechat_pay',
              transaction_id = ?,
              updated_at = NOW()
          WHERE id = ?
        `;

        await query(updateQuery, [payResult.data.transaction_id, orderId]);

        return res.json({
          success: true,
          data: {
            order_number: order.order_number,
            status: 'in_progress',
            amount: order.final_amount,
            transaction_id: payResult.data.transaction_id
          }
        });
      }
    }

    // 处理尾款支付状态查询
    if (order.status === 'pending_additional_payment') {
      let paymentMethodJson = {};
      try {
        paymentMethodJson = order.payment_method ? JSON.parse(order.payment_method) : {};
      } catch (e) {
        paymentMethodJson = {};
      }

      if (paymentMethodJson.additional_payments && Array.isArray(paymentMethodJson.additional_payments)) {
        let hasUpdates = false;

        // 查询每个待处理的尾款支付状态
        for (let payment of paymentMethodJson.additional_payments) {
          if (payment.status === 'PENDING' && payment.out_trade_no) {
            try {
              const payResult = await WechatPayService.queryOrder(payment.out_trade_no);

              if (payResult.success && payResult.data.trade_state === 'SUCCESS') {
                // 更新这笔尾款的状态
                payment.status = 'SUCCESS';
                payment.transaction_id = payResult.data.transaction_id;
                payment.paid_at = new Date().toISOString();
                hasUpdates = true;

                console.log(`✅ 尾款支付状态已更新 - out_trade_no: ${payment.out_trade_no}, 状态: SUCCESS`);
              }
            } catch (error) {
              console.error(`❌ 查询尾款支付状态失败 - out_trade_no: ${payment.out_trade_no}`, error);
            }
          }
        }

        // 如果有更新，重新计算订单状态和金额
        if (hasUpdates) {
          const totalAmount = parseFloat(order.total_amount);
          const currentFinal = parseFloat(order.final_amount);
          const discountAmount = parseFloat(order.discount_amount) || 0;

          // 计算已成功支付的尾款总额
          const successfulAdditionalPayments = paymentMethodJson.additional_payments
            .filter(p => p.status === 'SUCCESS')
            .reduce((sum, p) => sum + parseFloat(p.amount || 0), 0);

          const newFinal = Math.round((currentFinal + successfulAdditionalPayments) * 100) / 100;
          // 计算应付金额：总费用 - 优惠券折扣（优惠券永久有效）
          const shouldPayAmount = Math.max(0, totalAmount - discountAmount);
          const shouldComplete = newFinal >= shouldPayAmount - 0.005;

          // 若已补齐且存在实际离场时间，则直接完成订单
          const orderInfo = await query('SELECT actual_end_time FROM orders WHERE id = ?', [orderId]);
          const hasActualEnd = orderInfo.length > 0 && !!orderInfo[0].actual_end_time;
          const newStatus = shouldComplete ? (hasActualEnd ? 'completed' : 'in_progress') : 'pending_additional_payment';

          const updateQuery = `
            UPDATE orders
            SET final_amount = ?,
                status = ?,
                payment_method = ?,
                updated_at = NOW()
            WHERE id = ?
          `;

          await query(updateQuery, [shouldComplete ? shouldPayAmount : newFinal, newStatus, JSON.stringify(paymentMethodJson), orderId]);

          return res.json({
            success: true,
            data: {
              order_number: order.order_number,
              status: newStatus,
              amount: shouldComplete ? shouldPayAmount : newFinal,
              total_amount: totalAmount,
              additional_payments_updated: true
            }
          });
        }
      }
    }

    // 返回当前状态
    res.json({
      success: true,
      data: {
        order_number: order.order_number,
        status: order.status,
        amount: order.final_amount
      }
    });

  } catch (error) {
    console.error('查询支付状态错误:', error);
    res.status(500).json({
      success: false,
      message: '查询失败'
    });
  }
};

/**
 * 获取并绑定用户手机号
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
const bindPhoneNumber = async (req, res) => {
  try {
    const { code } = req.body;
    const userId = req.user.id;

    console.log('📱 绑定手机号请求 - 用户ID:', userId, 'code:', code?.substring(0, 10) + '...');

    if (!code) {
      return res.status(400).json({
        success: false,
        message: '缺少手机号授权码'
      });
    }

    if (!userId) {
      return res.status(401).json({
        success: false,
        message: '用户未登录'
      });
    }

    let phoneNumber = null;

    // 检查是否为开发环境
    if (code.startsWith('mock_phone_') || process.env.NODE_ENV === 'development') {
      console.log('🎭 开发环境检测到，使用模拟手机号');
      phoneNumber = '13800138000'; // 模拟手机号
    } else {
      // 获取微信手机号
      const WechatAuthService = require('../services/WechatAuthService');
      const result = await WechatAuthService.getPhoneNumber(code);

      if (result.success) {
        phoneNumber = result.data.purePhoneNumber || result.data.phoneNumber;
        console.log('✅ 获取微信手机号成功:', phoneNumber);
      } else {
        // 如果微信API调用失败，在开发环境中使用模拟数据
        if (process.env.NODE_ENV === 'development') {
          console.log('🎭 微信API调用失败，开发环境使用模拟手机号');
          phoneNumber = '13800138000';
        } else {
          return res.status(400).json({
            success: false,
            message: result.error || '获取手机号失败'
          });
        }
      }
    }

    // 检查手机号是否已被其他用户绑定
    const existingUserQuery = 'SELECT id, nickname FROM users WHERE phone_number = ? AND id != ?';
    const existingUsers = await query(existingUserQuery, [phoneNumber, userId]);

    if (existingUsers.length > 0) {
      return res.status(400).json({
        success: false,
        message: '该手机号已被其他用户绑定'
      });
    }

    // 更新用户手机号
    const updateQuery = `
      UPDATE users 
      SET phone_number = ?
      WHERE id = ?
    `;

    await query(updateQuery, [phoneNumber, userId]);

    // 获取更新后的用户信息
    const userQuery = 'SELECT id, nickname, avatar_url, phone_number, openid FROM users WHERE id = ?';
    const users = await query(userQuery, [userId]);
    const user = users[0];

    console.log('✅ 手机号绑定成功 - 用户ID:', userId, '手机号:', phoneNumber);

    res.json({
      success: true,
      message: '手机号绑定成功',
      data: {
        userInfo: {
          id: user.id,
          nickname: user.nickname,
          avatar: user.avatar_url,
          phone: user.phone_number,
          openid: user.openid
        }
      }
    });

  } catch (error) {
    console.error('绑定手机号错误:', error);

    // 在开发环境中，即使出错也尝试返回模拟绑定
    if (process.env.NODE_ENV === 'development') {
      console.log('🎭 绑定手机号出错，开发环境返回模拟绑定成功');
      
      return res.json({
        success: true,
        message: '开发环境模拟绑定成功',
        data: {
          userInfo: {
            id: req.user.id,
            nickname: '开发测试用户',
            avatar: '',
            phone: '13800138000',
            openid: 'mock_openid_dev'
          }
        }
      });
    }

    res.status(500).json({
      success: false,
      message: '绑定手机号失败，请重试'
    });
  }
};

module.exports = {
  getBanners,
  getParkingCategories,
  getParkingLots,
  getParkingLotById,

  searchParkingLots,
  getRecommendedParkingLots,
  getPopularParkingLots,
  createOrder,
  getParkingPrice,
  getAvailableCoupons,
  validateCoupon,
  payOrder,
  payAdditionalAmount,
  cancelOrder,
  getUserOrders,
  getUserOrderById,
  submitOrderReview,
  getUserCoupons,
  getUserRole,
  getUserProfile,
  getAvailableCouponTemplates,
  claimCoupon,
  getCustomerServiceConfig,
  handlePaymentNotify,
  handleRefundNotify,
  queryPaymentStatus,
  getOpenid,
  wxLogin,
  mockPaymentSuccess,
  bindPhoneNumber
};
